package com.tang.common.utils;

import io.jsonwebtoken.*;
import org.springframework.stereotype.Component;

import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.*;

@Component
public class JwtUtil {
    // 加密KEY
    private static final String TOKEN_ENCRY_KEY = "MDk4ZjZiY2Q0NjIxZDM3M2NhZGU0ZTgzMjYyN2I0ZjY";
    // 过期时间10小时
    private final static long TOKEN_EXPIRATION = 10*3600*1000L;
    // 最小刷新间隔(S)
    private static final int REFRESH_TIME = 600;

    /**
     * 生成token
     * @param username 用户名
     * @param password 密码
     * @return token
     */
    public static String generateToken(String username, String password,String role){
        Map<String, Object> claimMap = new HashMap<>();
        claimMap.put("username",username);
        claimMap.put("password",password);
        claimMap.put("role",role);
        return Jwts.builder()
                .setId(UUID.randomUUID().toString())
                .setHeaderParam("typ","JWT")
                .setHeaderParam("alg","HS256")
                //签发时间
                .setIssuedAt(new Date(System.currentTimeMillis()))
                //说明
                .setSubject("system")
                //签发者信息
                .setIssuer("tang")
                //接收用户
                .setAudience("app")
                //数据压缩方式
                .compressWith(CompressionCodecs.GZIP)
                //加密方式
                .signWith(SignatureAlgorithm.HS512, generalKey())
                //过期时间戳
                .setExpiration(new Date(System.currentTimeMillis()+TOKEN_EXPIRATION))
                //claim信息
                .addClaims(claimMap)
                .compact();
    }
    /**
     * 由字符串生成加密key
     *
     * @return
     */
    public static SecretKey generalKey() {
        byte[] encodedKey = Base64.getEncoder().encode(TOKEN_ENCRY_KEY.getBytes());
        SecretKey key = new SecretKeySpec(encodedKey, 0, encodedKey.length, "AES");
        return key;
    }
    /**
     * 获取token中的claims信息
     *
     * @param token
     * @return
     */
    private static Jws<Claims> getJws(String token) {
        return Jwts.parser()
                .setSigningKey(generalKey())
                .parseClaimsJws(token);
    }
    /**
     * 获取payload body信息
     *
     * @param token
     * @return
     */
    public static Claims getClaimsBody(String token) {
        try {
            return getJws(token).getBody();
        }catch (ExpiredJwtException e){
            return null;
        }
    }
    /**
     * 获取hearder body信息
     *
     * @param token
     * @return
     */
    public static JwsHeader getHeaderBody(String token) {
        return getJws(token).getHeader();
    }

    /**
     * 从token中获取key的值
     * @param jwtToken token
     * @param key key
     * @return value
     */
    public static String get(String jwtToken,String key){
        Claims claims = getClaimsBody(jwtToken);
        String value = claims.get(key,String.class);
        return value;
    }
    /**
     * 是否过期
     *
     * @String token
     * @return -1：有效，0：即将有效，1：过期，2：过期
     */
    public static int verifyToken(String token) {
        Claims claims = getClaimsBody(token);
        if(claims==null){
            return 1;
        }
        try {
            claims.getExpiration()
                    .before(new Date());
            // 需要自动刷新TOKEN
            if((claims.getExpiration().getTime()-System.currentTimeMillis())>REFRESH_TIME*1000){
                return -1;
            }else {
                //快过期，刷新token
                return 0;
            }
        } catch (ExpiredJwtException ex) {
            return 1;
        }catch (Exception e){
            return 2;
        }
    }
/*    public static void main(String[] args) {
       *//* Map map = new HashMap();
        map.put("id","11");*//*
        System.out.println(JwtUtil.generateToken("admin","admin"));
//        System.out.println(get("eyJhbGciOiJIUzUxMiIsInppcCI6IkdaSVAifQ.H4sIAAAAAAAAAD2MWw7CIBBF9zLfJQFaHnY3Q0GDCUg6EDWmey9o4t99nfuBe42wAi4XbbxTzKnrzBYjkVm5IRMcnTBccr_NMEHECqvQSnCrNDcTUHOdpjfVkEZP1G3FfOsGmx_PpXQdXuUHCmntAAsSPR_7d-FTzH3TKOwZU_hHxwnY7Uz9ngAAAA.ulbChEqT5GSPYyQIsWlZcBJNzzEMwr0bQq7-z1JdUWypgTCnGpQnrvrueHvAH7ZuA_o1WKOC3cyvYvprCY7hfQ","username"));
        Claims claimsBody = getClaimsBody(JwtUtil.generateToken("admin", "admin"));
        boolean before = claimsBody.getExpiration().before(new Date());
        System.out.println(before);

    }*/


}
